<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>函数节流</title>
</head>
<body style="height: 9000px;">
    <script>
        n=0;
        function scrollHandler(){
            console.log(new Date().getTime());
            console.log(++n);
        }

        // function throttle(method,delay){
        //     var timer=null;
        //     return function(){
        //         var context=this, args=arguments;
        //         clearTimeout(timer);
        //         timer=setTimeout(function(){
        //             method.apply(context,args);
        //         },delay);
        //     }

        // }

        function throttle(method,delay,duration){
            var delay = delay || 50;
            var duration = duration || 100;
            var timer=null, begin=new Date();
            return function(){
                var context=this, args=arguments, current=new Date();
                clearTimeout(timer);
                if(current-begin>=duration){
                     method.apply(context,args);
                     begin=current;
                }else{
                    timer=setTimeout(function(){
                        method.apply(context,args);
                    },delay);
                }
            }
        }

        // window.onscroll=throttle(scrollHandler,500)
        window.onscroll=throttle(scrollHandler,1000,5000);
    </script>
</body>
</html>